package com.tidy.seed.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.util.ContentCachingRequestWrapper;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Component
@Order(Ordered.HIGHEST_PRECEDENCE) // 确保过滤器在最前面执行
public class RequestBodyCacheFilter implements Filter {
    private static final Logger log = LoggerFactory.getLogger(RequestBodyCacheFilter.class);

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        if (request instanceof HttpServletRequest) {
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            log.info("进入RequestBodyCacheFilter，原始请求类型: {}", request.getClass().getName());
            log.info("请求头 - Content-Type: {}, Content-Length: {}",
                    httpRequest.getHeader("Content-Type"),
                    httpRequest.getHeader("Content-Length"));
            log.info("处理请求: {} {}", httpRequest.getMethod(), httpRequest.getRequestURI());

            // 关键：仅用ContentCachingRequestWrapper包装请求，不手动读取流
            ContentCachingRequestWrapper wrappedRequest = new ContentCachingRequestWrapper(httpRequest);

            // 直接传递包装后的请求，让框架自动触发缓存
            chain.doFilter(wrappedRequest, response);
            log.info("过滤器处理完成，已传递包装后的请求");
        } else {
            chain.doFilter(request, response);
            log.info("非HttpServletRequest，直接放行");
        }
    }

    // 初始化和销毁方法（默认空实现即可）
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {
    }
}